package com.dataart.productshop.controller;

import com.dataart.productshop.Constants;
import com.dataart.productshop.file.utils.StringUtils;
import com.dataart.productshop.model.boiko.informationsystem.Kathedra;
import com.dataart.productshop.model.boiko.informationsystem.Subject;
import com.dataart.productshop.service.KathedraManager;
import com.dataart.productshop.service.SubjectManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

@Controller
public class AddKathedraController {

    @Autowired
    KathedraManager kathedraManager;

    @RequestMapping(value = "/addKathedra", method = RequestMethod.GET)
    public ModelAndView createSubjectGet(){
        return standartKathPage();
    }

    @RequestMapping(value = "/addKathedra", method = RequestMethod.POST)
    public ModelAndView createSubjectPost(@RequestParam(Constants.NEW_ELEMENT_NAME) String kathedraName){
        System.out.println(kathedraName);
        if(!StringUtils.isEmpty(kathedraName)){
            Kathedra kath = new Kathedra();
            kath.setName(kathedraName);
            kathedraManager.save(kath);
        }

        return standartKathPage();
    }

    @RequestMapping(value = "/remove" + Constants.KATHEDRA_TYPE + "/{itemId}"
            , method = RequestMethod.GET)
    public String removeKathedra(@PathVariable("itemId") String itemId){
        try{
            kathedraManager.delete(Long.parseLong(itemId));
        }catch (NumberFormatException e){

        }catch(Exception dd){
            System.err.println("some exception were occured in AssKathedra controller"
                    + dd.getStackTrace());
        }

        return "redirect:/addKathedra";
    }

    private ModelAndView standartKathPage(){
        Map<String, Object> viewElements= new HashMap<String, Object>();
        viewElements.put(Constants.KATHEDRA_N_SUBJECT_LIST_NAME, kathedraManager.getAll());
        viewElements.put(Constants.KATHEDRA_N_SUBJECT_CURRENT_TYPE, Constants.KATHEDRA_TYPE);
        viewElements.put(Constants.NEW_ELEMENT_NAME, Constants.NEW_ELEMENT_NAME);
        return new ModelAndView("addSubjectOrKathedra", viewElements);
    }
}
